package com.ht.medicaltreatment.activity

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.MultiSampleCollectionAdapter
import com.ht.medicaltreatment.bean.Drawblood
import com.ht.medicaltreatment.utils.BloodScanErrorDialog
import com.ht.medicaltreatment.utils.DownTimeUtils
import com.ht.medicaltreatment.utils.NFCUtils
import com.ht.medicaltreatment.utils.ScanUtils
import com.ht.medicaltreatment.utils.SoundUtils
import com.ht.medicaltreatment.utils.UIDUitls
import com.ht.medicaltreatment.view.BloodItemPop
import com.ht.medicaltreatment.view.BloodRemarkDialog
import com.ht.medicaltreatment.view.ReplaceCaiXueDialog
import com.ht.medicaltreatment.viewmodel.SingleViewModel
import com.xgst.lib.utils.showToast
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.android.synthetic.main.activity_multi_blood_collection_detail_layout.tvBloodLocation
import kotlinx.android.synthetic.main.activity_multi_blood_collection_detail_layout.tvQX
import kotlinx.android.synthetic.main.activity_multi_blood_collection_detail_layout.tvRoomCode
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.groupHY
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.groupHYState
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgCYD
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgJump
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgNext
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgRed
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgScan
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgStation
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgTH
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.llRemarks
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.llStartTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.progress
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.progressGroup
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.recyclerView
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvAfterTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvCode
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvDownTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvLJCY
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvName
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvPlanCXTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvPlanTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvPreTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvSex
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvStartCheck
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvStation
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvTubeName
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvYear
import java.text.SimpleDateFormat

/**
 * 多管
 */
class BloodSpecimenCollectionDetailActivity:BaseActivity(), View.OnClickListener {

    override fun getLayoutId() = R.layout.activity_multi_blood_collection_detail_layout

    //存放备注信息
    private var map:MutableMap<String,String> = mutableMapOf()
    private lateinit var adapter:MultiSampleCollectionAdapter
    private val model by viewModels<SingleViewModel>()
    private var isNFC = false
    private lateinit var replaceCaiXueDialog: ReplaceCaiXueDialog
    //前时间窗 分钟
    private var preTimeMinute = 0f
    // 分钟
    private var afterTimeMinute = 0f
    private var orderId = 0
    private var isAllChecked = false
    private var isCaiXue = false
    private var isReplace = false
    private var afterTime = 0L
    private var preTime = 0L
    private var planTime:Long = 0L
    private var checkSuccess = 0
    private var drawBloodOrderId = 0
    private var drawBloodId = 0
    private var isOpen = false
    private lateinit var mediaplayer:MediaPlayer
    private var disposable:Disposable?=null
    private var disposable2:Disposable?=null
    //来自条形码
    private var isBarCode = false

    override fun init() {
        setTitle("样本采集")

        mediaplayer = MediaPlayer.create(this, R.raw.after_collection_blood30)
        mediaplayer.setLooping(false)

        val uid = intent.getStringExtra("uid")?:""
        val isOrder = intent.getBooleanExtra("isOrder",false)
        replaceCaiXueDialog = ReplaceCaiXueDialog(this)
        adapter = MultiSampleCollectionAdapter()
        recyclerView.layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
        recyclerView.adapter = adapter

        initClick()

        if(Build.MODEL == "V9100"){
            ScanUtils.init()
        }else{
            isNFC = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC)
            if(isNFC){
                NFCUtils(this)
            }
        }

        val drawbloodList = intent.getParcelableArrayListExtra<Drawblood>("bloodList")

        if(drawbloodList != null && drawbloodList.size > 0){
            adapter.setNewInstance(drawbloodList)

            val it = drawbloodList!![0]
            tvName.text = it.patientInformation?.patientName
            tvSex.text = it.patientInformation?.patientSex
            tvCode.text = it.patientInformation?.urineRfidCode
            val sb = StringBuilder()
            drawbloodList.forEachIndexed { index, drawblood ->
                if(index != drawbloodList.size - 1){
                    sb.append(drawblood.name)
                    sb.append("\n")
                }else{
                    sb.append(drawblood.name)
                }
            }
            tvTubeName.text = sb.toString()
            orderId = it.drawbloodMoreOrder?.id?:0

            initView(it)
        }else{
            model.wanDai(uid,isOrder,{
                tvName.text = it.patientInformation.patientName
                tvSex.text = it.patientInformation.patientSex
                tvCode.text = it.patientInformation.patientCode
                orderId = it.drawBloodMoreOrder?.id?:0
                it.patientInformation.ward.remarks
                //每个时间点只有一根试管
                if(it.drawBloodMoreOrder?.bloodNum == 1){
                    val item = it.drawbloodList.first { it.checkSuccess == 0 }
                    adapter.addData(item)
                    tvTubeName.text = item.name
                    initView(item)
                }else{
                    //多管
                    val drawbloodList = it.drawbloodList
                    var startIndex = 0
                    //当前时间点
                    while (startIndex < drawbloodList.size){
                        var over = false
                        val bloodGroupSum = drawbloodList[startIndex].bloodGroupSum
                        //当前时间点的管
                        for(i in 0 until bloodGroupSum){
                            if(i+startIndex >= it.drawbloodList.size)return@wanDai
                            val drawblood = it.drawbloodList[i+startIndex]
                            if(drawblood.checkSuccess == 0){
                                over = true
                            }
                            adapter.addData(drawblood)
                        }
                        //都不为0的话，表示没有需要采血的管子
                        if (over){
                            val sb = StringBuilder()
                            adapter.data.forEachIndexed { index, drawblood ->
                                if(index != drawbloodList.size - 1){
                                    sb.append(drawblood.name)
                                    sb.append("\n")
                                }else{
                                    sb.append(drawblood.name)
                                }
                            }
                            tvTubeName.text = sb.toString()

                            initView(adapter.data[0])
                            return@wanDai
                        }
                        adapter.data.clear()
                        startIndex = startIndex + bloodGroupSum
                    }
                }
            },{
                showToast(it)
            })
        }
    }

    private fun initView(item: Drawblood) {
        drawBloodOrderId = item.drawbloodMoreOrder?.id?:0
        drawBloodId = item.id
        preTimeMinute = item.preTimeStamp?.toFloat() ?: 0f
        afterTimeMinute = item.afterTimeStamp?.toFloat() ?: 0f

        //红点位置
        redLocation()

        val expectTime = item.expectTime
        tvPreTime.text = item.preTimeStamp
        tvAfterTime.text = item.afterTimeStamp
        tvPlanTime.text = expectTime

        checkSuccess = item.checkSuccess

        if(checkSuccess == 1){
            //回显 - 核验正常，并且已经采血
            groupHY.visibility = View.GONE
            groupHYState.visibility = View.VISIBLE

            imgStation.setBackgroundResource(R.drawable.icon_heyan_success)
            tvStation.text = "采样正常"
            tvStation.setTextColor(getColor(R.color.green))

            tvPlanCXTime.text = "计划采血时间:${tvPlanTime.text}"
            progressGroup.visibility = View.INVISIBLE
            imgRed.visibility = View.GONE
        } else if(checkSuccess == 2){
            // 回显 - 已超窗
            groupHY.visibility = View.GONE
            groupHYState.visibility = View.VISIBLE

            imgStation.setBackgroundResource(R.drawable.icon_chaochuang)
            tvStation.text = "采样超窗"
            tvStation.setTextColor(getColor(R.color.red))

            tvPlanCXTime.text = "计划采血时间:${tvPlanTime.text}"
            progressGroup.visibility = View.INVISIBLE
            imgRed.visibility = View.GONE

        }else if(checkSuccess == 3){
            //回显 - 紧急跳过
            groupHY.visibility = View.GONE
            groupHYState.visibility = View.VISIBLE

            imgStation.setBackgroundResource(R.drawable.icon_jjtg)
            tvStation.text = "紧急跳过"
            tvStation.setTextColor(getColor(R.color.orange))

            progressGroup.visibility = View.INVISIBLE
            imgRed.visibility = View.GONE

        }

        if(checkSuccess == 0){
            startDownTime(expectTime)
        }

        //多少根试管就添加多少个备注按钮和采血按钮
        adapter.data.forEach { item ->
            val remark = LayoutInflater.from(this).inflate(R.layout.include_remark_layout,null,false)
            val blood = LayoutInflater.from(this).inflate(R.layout.include_collection_blood_layout,null,false)
            remark.findViewById<TextView>(R.id.tvInputMark).text = "点击添加备注信息\n${item.name}"
            remark.tag = item.name
            blood.tag = item.name

            val tvStartTime = blood.findViewById<TextView>(R.id.tvStartTime)
            if(item.actualTime != null){
                tvStartTime.text = "采血时间: ${item.actualTime}\n${item.name}"
                tvStartTime.setTextColor(getColor(R.color.color97))
            }else{
                tvStartTime.text = "点击记录采样时间\n${item.name}"
            }

            //TODO 备注按钮的点击事件
            remark.setOnClickListener {
                BloodRemarkDialog(this).show(item.otherRemark?:""){etRemark ->
                    //发送备注信息
                    showProgress()
                    model.updateDrawblood("${item.id}",etRemark){
                        dismissProgress()
                        showToast("备注成功")
                    }
                }
            }

            //TODO 点击记录采血时间  采血按钮的点击事件
            blood.setOnClickListener {
                if(tvStation.text.toString() == "紧急跳过"){
                    showToast("已跳过，无法采血")
                    return@setOnClickListener
                }
                if(!isCheckAll()){
                    showToast("您还未完成核验")
                    return@setOnClickListener
                }
                val tvStartTime = blood.findViewById<TextView>(R.id.tvStartTime)

                if(checkSuccess == 1 || checkSuccess == 2){
                    showToast("已记录采血时间，无需重复记录")
                    return@setOnClickListener
                }

                if(checkSuccess == 3){
                    showToast("已紧急跳过")
                    return@setOnClickListener
                }

                if(isOver()){
                    //超窗,必须填写备注才可以记录采血时间
                    SoundUtils.playSound(SoundUtils.OUT_OF_WINDOW)
                    BloodRemarkDialog(this).show(item.otherRemark?:""){remark ->
                        val nowTime = TimeUtils.getNowString()
                        showProgress()
                        model.addRemarks(nowTime,"${item.id}",remark){
                            dismissProgress()
                            //修改试管颜色为采血颜色
                            adapter.data.find { it.checkSuccess != 4 }?.checkSuccess = 4
                            adapter.notifyDataSetChanged()
                            if( !tvStartTime.text.contains("采血时间")){
                                tvStartTime.text = "采血时间:$nowTime\n${item.name}"
                                tvStartTime.setTextColor(getColor(R.color.color97))
                                collectBloodTime()
                            }
                        }
                    }
                }else{
                    //没有超窗  记录采血时间
                    showProgress()
                    model.bloodCollectionTime(TimeUtils.getNowString(), "${item.id}"){
                        dismissProgress()
                        if(!tvStartTime.text.contains("采血时间")){
                            tvStartTime.text = "采血时间:${TimeUtils.getNowString()}\n${item.name}"
                            tvStartTime.setTextColor(getColor(R.color.color97))
                            collectBloodTime()
                        }
                    }
                    //修改试管颜色为采血颜色
                    adapter.data.find { it.checkSuccess != 4 }?.checkSuccess = 4
                    adapter.notifyDataSetChanged()
                }
            }

            llRemarks.addView(remark)
            llStartTime.addView(blood)
        }
    }

    /**
     * 开始执行倒计时计划
     */
    private fun startDownTime(expectTime:String?) {
        //计划采血时间
        planTime = TimeUtils.string2Millis(expectTime, "yyyy-MM-dd HH:mm:ss")
        if (!isOver()) {
            //没超窗
            SoundUtils.playSound(SoundUtils.WINDOW_BEGIN)

            val s = (planTime - TimeUtils.getNowMills())/1000 >= 32
            LogUtils.i("大于计划时间 $s")
            if(s){
                disposable = DownTimeUtils.downTime((planTime - TimeUtils.getNowMills())/1000){
                    if(it == 30L){
                        mediaplayer = MediaPlayer.create(this,R.raw.after_collection_blood30)
                        mediaplayer.start()
                        disposable!!.dispose()
                    }
                }
            }

            val maxTime = (afterTime - preTime) / 1000
            val downTime = (afterTime - TimeUtils.getNowMills())/1000
            tvLJCY.text = "请立即采样"
            progress.setMaxProgress(maxTime.toFloat())
            //偏移量
            val offsetTime = (TimeUtils.getNowMills() - preTime)/1000
            disposable2 = DownTimeUtils.downTime(downTime){
                tvDownTime.text = "$it"
                progress.setProgress(offsetTime+(downTime - it).toFloat())
                if(it == 30L){
                    //距离超窗还有30秒
                    mediaplayer = MediaPlayer.create(this,R.raw.after_outof_window30)
                    mediaplayer.start()
                }
            }

        } else {
            val currentTime = TimeUtils.getNowMills()
            if(currentTime < preTime){
                //超窗  还没到采血时间
                tvLJCY.text = "还未到采样时间"
                /**
                 * 1、设置最大进度是  前时间窗 -> 后时间窗之间的距离
                 * 2、第一个倒计时是  当前时间 -> 前时间窗 (距离开始采血的时间)
                 * 3、第二个倒计时   当前时间(前时间窗) -> 后时间窗 （距离超窗的时间）
                 * 4、红点的位置     计划时间 距离前时间窗的距离  占据这个进度的百分比
                 */
                //1、设置最大进度
                val maxProgress = (afterTime - preTime)/1000
                progress.setMaxProgress(maxProgress.toFloat())
                //2、第一个倒计时是  当前时间 -> 前时间窗 (距离前时间窗的时间)
                disposable = DownTimeUtils.downTime((preTime-currentTime)/1000,{
                    tvDownTime.text = "$it"
                    if(it == 0L){
                        LogUtils.i("进入时间窗",Thread.currentThread().name,maxProgress)
                        //进入时间窗
                        mediaplayer = MediaPlayer.create(this,R.raw.window_begin)
                        mediaplayer.start()
                        //达到前时间窗位置
                        tvLJCY.text = "请立即采样"
                        disposable = DownTimeUtils.downTime(maxProgress,{
                            progress.setProgress((maxProgress - it).toFloat())
                            tvDownTime.text = "$it"
                            if(it == 30L){
                                //距离超窗还有30秒
                                mediaplayer = MediaPlayer.create(this,R.raw.after_collection_blood30)
                                mediaplayer.start()
                            }
                        })
                        //达到计划采样时间后，语音提示
                        disposable2 = DownTimeUtils.downTime((planTime - TimeUtils.getNowMills())/1000){
                            if(it == 30L){
                                mediaplayer = MediaPlayer.create(this,R.raw.after_collection_blood30)
                                mediaplayer.start()
                            }
                        }
                    }
                })
            }

            if(currentTime > afterTime){
                //超窗
                tvLJCY.text = "已超窗"
                tvLJCY.setTextColor(Color.RED)
                tvDownTime.text = "0"
                progress.setMaxProgress(1f)
                progress.setProgress(1f)
            }
        }
    }

    private fun redLocation() {
        if(preTimeMinute == 0f)return
        //红点位置
        val percent: Float = preTimeMinute / (preTimeMinute + afterTimeMinute)
        val left: Float = percent * progress.width
        val params = imgRed.layoutParams as ConstraintLayout.LayoutParams
        params.leftMargin = left.toInt() - imgRed.width / 2
        imgRed.layoutParams = params
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        //红点位置
        redLocation()
    }

    private fun initClick() {
        imgTH.setOnClickListener(this)
        tvStartCheck.setOnClickListener(this)
        imgJump.setOnClickListener(this)
        imgNext.setOnClickListener(this)
        imgScan.setOnClickListener(this)
        imgCYD.setOnClickListener(this)
        tvRoomCode.setOnClickListener(this)
        tvBloodLocation.setOnClickListener(this)
        tvQX.setOnClickListener(this)
    }

    /**
     * 是否超长
     * true  超窗
     * fasle 没有
     */
    fun isOver():Boolean{
        val countTime = TimeUtils.getNowMills()
        preTime = planTime - (preTimeMinute*60*1000).toInt()
        afterTime = planTime + (afterTimeMinute*60*1000).toInt()
        //LogUtils.i(planTime,preTime,afterTime)
        val isOver = !(countTime > preTime && countTime < afterTime)
        //是否超窗
        return isOver
    }

    override fun onClick(v: View?) {
        when(v){
            //替换采血管
            imgTH -> {
                if(checkSuccess == 3){
                    showToast("已紧急跳过")
                    return
                }

                isReplace = true

                if(!isOpen){
                    scanOpen()
                }

                replaceCaiXueDialog.show(adapter.data){bloodId, uid,position ->
                    showProgress()
                    model.replace("$bloodId",uid,{
                        dismissProgress()
                        isReplace = false
                        showToast("替换成功")
                        adapter.data[position].rfidCode = uid
                    },{
                        dismissProgress()
                        showToast(it)
                    })
                }
            }

            //开始核验
            tvStartCheck -> {
                if(checkSuccess == 2 || checkSuccess == 3){
                    return
                }
                if(isOpen){
                    isOpen = false
                    tvStartCheck.text = "点击核验"
                    ScanUtils.close()
                    SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                }else{
                    if(!isCaiXue){
                        //groupHY.visibility = View.INVISIBLE
                        tvStartCheck.text = "停止核验"
                        tvYear.text = "${TimeUtils.getNowString(SimpleDateFormat("yyyy"))}\n${TimeUtils.getNowString(SimpleDateFormat("MM-dd"))}"
                        scanOpen()
                    }
                }
            }

            //紧急跳过
            imgJump -> {
                if(isCaiXue || checkSuccess == 1 || checkSuccess == 2 ){
                    showToast("已采血，无法跳过")
                    return
                }

                if(checkSuccess == 3){
                    showToast("已紧急跳过")
                    return
                }

                showProgress()
                model.caixueJump("$drawBloodId"){
                    dismissProgress()
                    imgStation.setBackgroundResource(R.drawable.icon_jjtg)
                    tvStation.text = "紧急跳过"
                    tvStation.setTextColor(getColor(R.color.orange))
                    progressGroup.visibility = View.INVISIBLE
                    imgRed.visibility = View.GONE
                    groupHY.visibility = View.GONE
                    groupHYState.visibility = View.VISIBLE
                }
            }

            //下一个受试者
            imgNext -> {
                startActivity(NFCActivity::class.java)
                finish()
            }

            //扫描核验
            imgScan -> {
                if(checkSuccess == 0){
                    val intent = Intent(this,ScanZBarActivity::class.java)
                    startActivityForResult(intent,101)
                }
            }

            //查看采样点
            imgCYD -> {
                val intent = Intent(this,FormRecordActivity::class.java)
                intent.putExtra("uid",drawBloodOrderId)
                startActivity(intent)
                finish()
            }

            //采血房间号
            tvRoomCode -> {
                BloodItemPop(this).show { s, i ->

                }
            }

            //采血部位
            tvBloodLocation -> {

            }

            //采血器械
            tvQX -> {

            }
        }
    }

    //扫码
    private fun scanOpen() {
        if(Build.MODEL == "V9100"){
            isOpen = true
            ScanUtils.open {uid->
                SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                isBarCode = false
                startCheck(uid)
            }
        }
    }

    private fun collectBloodTime() {
        isCaiXue = true
        SoundUtils.playSound(SoundUtils.RECORD_TIME)
        groupHYState.visibility = View.VISIBLE
        if (!isOver()) {
            //采血正常
            imgStation.setBackgroundResource(R.drawable.icon_heyan_success)
            tvStation.text = "采样正常"
        } else {
            imgStation.setBackgroundResource(R.drawable.icon_chaochuang)
            tvStation.text = "采样超窗"
            tvStation.setTextColor(getColor(R.color.red))
        }

        tvPlanCXTime.text = "计划采血时间:${tvPlanTime.text}"
        progressGroup.visibility = View.INVISIBLE
        imgRed.visibility = View.GONE
    }

    //开始核验
    private fun startCheck(uid: String) {

        ScanUtils.resetItem(uid)

        if (isReplace) {
            replaceCaiXueDialog.setUID(uid)
            return
        }

        adapter.data.forEachIndexed { index, item ->
            if (uid == item.rfidCode || uid == item.barCode) {
                SoundUtils.playSound(SoundUtils.CHECK_SUCCESS)
                item.scanTime = TimeUtils.getNowString(SimpleDateFormat("HH:mm:ss"))
                adapter.notifyItemChanged(index)
                if (isCheckAll()) {
                    submitData()
                }
                //核验正确 不往下走了
                return
            }
        }

        //核验错误，通过接口获取试管的名字，弹框提示
        showProgress()
        var noUid = ""
        adapter.data.forEach {
            if (noUid == "") {
                noUid = it.name?:"--"
            } else {
                noUid = "$noUid\n${it.name}"
            }
        }
        if(isBarCode){
            //数据来自条形码
            model.searchNameByBarCode(arrayListOf(uid), {
                dismissProgress()
                BloodScanErrorDialog(this).show(noUid, it[0])
                ScanUtils.resetItem(uid)
            }, {
                ScanUtils.resetItem(uid)
                dismissProgress()
                showToast(it)
            })
        }else{
            model.searchName(arrayListOf(uid), {
                dismissProgress()
                BloodScanErrorDialog(this).show(noUid, it[0])
                ScanUtils.resetItem(uid)
            }, {
                ScanUtils.resetItem(uid)
                dismissProgress()
                showToast(it)
            })
        }
        SoundUtils.playSound(SoundUtils.CHECK_ERROR)
    }

    //核验完毕  提交核验时间
    private fun submitData() {
        isAllChecked = true
        //全部核验完毕 记录核验时间
        //ScanUtils.close()
        var id = ""
        adapter.data.forEach {
            if (id == "") {
                id = "${it.id}"
            } else {
                id = "$id,${it.id}"
            }
        }
        model.recordCheckTime(id){
            showToast("已记录核验时间")
        }
    }

    override fun onResume() {
        super.onResume()
        if(!isNFC)return
        //开启前台调度系统
        NFCUtils.mNfcAdapter.enableForegroundDispatch(this,
            NFCUtils.mPendingIntent,
            NFCUtils.mIntentFilter, NFCUtils.mTechList)
    }

    override fun onPause() {
        super.onPause()
        if(!isNFC)return
        //关闭前台调度系统
        NFCUtils.mNfcAdapter.disableForegroundDispatch(this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == 101){
            val uid = data?.getStringExtra("resultUid")
            if (uid == null)return
            isBarCode = true
            startCheck(uid)
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if(!isNFC)return
        //当该Activity接收到NFC标签时，运行该方法
        //调用工具方法，读取NFC数据
        var uid: String = NFCUtils.readNFCId(intent)
        uid = UIDUitls.sort(uid)
        isBarCode = false
        startCheck(uid)
    }

    fun isCheckAll():Boolean {
        val bean = adapter.data.find { it.scanTime == null || it.scanTime == "" }
        if(bean == null){
            return true
        }else{
            return false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if(isOpen){
            ScanUtils.close()
            isOpen = false
        }
        if(disposable?.isDisposed == false){
            disposable?.dispose()
        }
        if(disposable2?.isDisposed == false){
            disposable2?.dispose()
        }
       // ScanUtils.onDestroy()
    }

}
